package features.advance.jdk.redis;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

/**
 * @author LIN
 * @date 2021-07-27
 */
public class LRUCache<K,V> {

    private Queue<K> queue = new LinkedList<>();
    private int cappacity = 0;

    private Map<K,V> map = new HashMap<>();
    public LRUCache(int cappacity){
        this.cappacity = cappacity;
    }


    public V get(K key){
        if(map.containsKey(key)) {
            queue.remove(key);
            queue.add(key);
        }
        return map.get(key);
    }
    public void put(K key,V value){
        if(queue.size() == this.cappacity){
            K poll = queue.poll();
            map.remove(poll);
        }
        queue.add(key);
        map.put(key,value);
    }

    public static void main(String[] args) {
        LRUCache cache = new LRUCache( 2 /* capacity */ );
        cache.put(1, 1);
        cache.put(2, 2);
        System.out.println(cache.get(1)); // returns 1
        cache.put(3, 3); // evicts key 2
        System.out.println(cache.get(2)); // returns -1 (not found)
        cache.put(4, 4); // evicts key 1
        System.out.println(cache.get(1)); // returns -1 (not found)
        System.out.println(cache.get(3)); // returns 3
        System.out.println(cache.get(4)); // returns 4

    }


}
